package pers.qianyu.interceptor;

import cn.hutool.log.*;
import com.google.common.util.concurrent.*;
import org.springframework.stereotype.*;
import org.springframework.web.servlet.*;
import pers.qianyu.exception.*;

import javax.servlet.http.*;

/**
 * 全局限流拦截器
 *
 * @author mizzle rain
 * @date 2020-10-14 10:04
 */
@Component
public class RateLimitInterceptor implements HandlerInterceptor {
    /**
     * 每秒的请求次数
     */
    private final RateLimiter limiter = RateLimiter.create(50);

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        if (!limiter.tryAcquire()) {
            LogFactory.get().error("接口被限流了");
            throw new BusinessException(GlobalErrorCodeEnum.RATE_LIMIT_ERROR);
        }
        return true;
    }
}
